<?php
namespace Modules\Activity\Http\Controllers\Client\Fudai;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Activity\Entities\Fudai\Activity;
use Modules\Activity\Entities\Fudai\Sku;

use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;


// 福袋订单
class CardController extends Controller
{
    // 创建订单
    public function use(Request $req) 
    {
        $rule = [
            'page_uuid' => ['required'],
            'card_type' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $types = [
            'show_box',
            'exclude_box'
        ];

        if (!in_array($req->card_type, $types)) {
            ThrowException::Conflict('非法的道具卡类型');
        }

        $user = Auth::requireLoginUser();

        $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

        // 福袋
        $activity = Activity::getEntity([
            'id' => $cached['fudai_id']
        ]);

        $sku = $activity->skus()->where('id', $cached['sku_id'])->first() ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

        $cardType = $req->card_type;

        // 扣除道具卡
        $useFlag =  $user->card_asset($cardType)->use(1, [
            'description' => '开福袋使用'
        ]);

        // 使用不成功，没有卡片
        if (!$useFlag) {
            $info = [
                'is_card_enought' =>  0
            ];
        }
        else {
            $only = [
                'id',
                'uuid',
                'title',
                'thumb',
                'number'
            ];

            if ($cardType === 'show_box') {
                $info = [
                    'is_card_enought' => 1,
                    'card_type' => 'show_box',
                    'skus' => $sku->getInfo($only)
                ];
            }
            elseif ($cardType === 'exclude_box') {

                $notSku = $activity->skus()->where('id', '<>', $sku->id)->inRandomOrder()->first();

                $info = [
                    'is_card_enought' => 1,
                    'card_type' => 'exclude_box',
                    'skus' => $notSku->getInfo($only)
                ];
            }
        }


        // 返回订单内容
        return $info;
    }
}
